package com.alex.monitor.core.alarm.impl;

import com.alex.monitor.core.alarm.MonitorAlarm;
import com.alex.monitor.core.annotation.MethodMonitor;
import com.alex.monitor.core.annotation.TimeMethodMonitor;
import com.alex.monitor.core.properties.AlexMonitorProperties;
import com.alibaba.fastjson2.JSONObject;
import java.lang.reflect.Method;

/**
 * @author Alex.Liu
 * @date: 2025-02-17 11:43
 * @since 1.0.0
 */
public abstract class AbstractMonitorAlarm implements MonitorAlarm {


    private final AlexMonitorProperties properties;

    public AbstractMonitorAlarm(AlexMonitorProperties properties) {
        this.properties = properties;
    }

    /**
     * 获取相应内容
     *
     * @param method
     * @param result
     * @return
     */
    protected JSONObject parseObj(Method method, Object result) {
        JSONObject obj = new JSONObject();
        obj.put("method", method.getDeclaringClass().getName() + "#" + method.getName());
        obj.put("result", result);
        return obj;
    }

    protected JSONObject parseEx(Method method, Throwable ex) {
        JSONObject obj = new JSONObject();
        obj.put("method", method.getDeclaringClass().getName() + "#" + method.getName());
        obj.put("error", ex.getMessage());
        obj.put("exception.class", ex.getClass().getName());
        return obj;
    }

    protected JSONObject parseTimeout(Method method, long timeCost) {
        JSONObject obj = new JSONObject();
        obj.put("method", method.getDeclaringClass().getName() + "#" + method.getName());
        obj.put("timeCost", timeCost + " MS");
        return obj;
    }

    protected String getTag(Method method) {
        return "Alex Monitor Alarm[" + method.getName() + "]";
    }

    @Override
    public void alarmObj(Method method, MethodMonitor annotation, Object result) {
        JSONObject message = this.parseObj(method, result);
        String tag = this.getTag(method);
        this.doAlarm(tag, message);
    }


    @Override
    public void alarmEx(Method method, MethodMonitor annotation, Throwable ex) {
        JSONObject message = this.parseEx(method, ex);
        String tag = this.getTag(method);
        this.doAlarm(tag, message);
    }

    @Override
    public void alarmTimeout(Method method, TimeMethodMonitor annotation, long timeCost) {
        JSONObject message = this.parseTimeout(method, timeCost);
        String tag = this.getTag(method);
        this.doAlarm(tag, message);
    }

    /**
     * 预警逻辑
     *
     * @param tag     签名
     * @param message 预警内容
     */
    protected abstract void doAlarm(String tag, JSONObject message);
}